package com.itheima.web.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet("/aServlet")
public class AServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //发送cookie

        //设置字符乱码问题
        request.setCharacterEncoding("utf-8");
        //1.创建cookie对象

        //URL编码解决value无法接收中文
        String value = "张三";
        value = URLEncoder.encode(value, "UTF-8");
        System.out.println("存储数据源："+value);

        Cookie cookie = new Cookie("username",value);    //value不能是中文，否则会报乱码错误 500

        //设置存活时间 3min
        cookie.setMaxAge(3 * 60);

        //2.发送Cookie.response
        response.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}